<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'../../model/Entity/Domain/InvoicesDomain.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'../../model/Entity/Domain/InvoicedetailsDomain.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'../../model/Service/InvoiceService.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'../../model/Service/InvoiceDetailService.php');
$authenticationService = new AuthenticationService();
$host = Tool::decode($smtp['host'], "sTunnInVietnAm@2012#");
$port = Tool::decode($smtp['port'], "sTunnInVietnAm@2012#");
$user = Tool::decode($smtp['user'], "sTunnInVietnAm@2012#");
$pass = Tool::decode($smtp['pass'], "sTunnInVietnAm@2012#");
$emailService = new EmailService($host, $port, $user, $pass);
$emailService->setSiteURL($glb['websiteURL']);
$orderService = new OrdersService();
$accountService = new AccountService();
$reportService = new ReportService();
switch ($action) {		
	case "add":
		if($permit == true)
		{
			$data = $_POST;
			print_r($data);
			
			$invoiceService = new InvoiceService();
			$shipmentService = new ShipmentService();
			$paymentService = new PaymentServices();
			$invoiceNumber = $invoiceService->getMaxInvoiceNumber($context, $result);
			if($invoiceNumber >= $num['invoiceNumber'])
			{
				$invoiceData['invoiceNumber'] = $invoiceNumber + 1;
			}
			else 
			{
				$invoiceData['invoiceNumber'] = $num['invoiceNumber'];
			}
			$invoiceData['orderID'] = $_POST['orderID'];
			$invoiceData['factoryID'] = $_SESSION['user']['ID'];
			$invoiceData['currency'] = $_POST['currency'];
			$invoiceData['commission'] = $_POST['commission'];
			$invoiceData['VAT'] = $_POST['VAT'];
			$invoiceData['containerNo'] = $_POST['containerNo'];
			
			$order = $orderService->getPurchaseOrderByPurchaseIDByFactoryID($context, $result, $_POST['orderID'], $_SESSION['user']['ID']);
			$orderDetailArr = $order->getOrderDetail();
			$totalAmount = 0;
			foreach ($orderDetailArr as $orderDetail)
			{
				foreach ($_POST as $key => $value)
				{
					if(is_numeric($key) && $key == $orderDetail->getArticle()->getArticleDomain()->getID())
					{
						$totalAmount += $orderDetail->getOrderdetailsDomain()->getPriceFact() * $value;
					}
				}
				
			}
			echo $totalAmount;
			$invoiceData['totalAmount'] = $totalAmount;
			$totalAfterComm = $totalAmount + ($totalAmount * $_POST['commission']/100);
			$toBePaid = $totalAfterComm + ($totalAfterComm * $_POST['VAT']/100);
			//echo $toBePaid;
			$invoiceData['toBePaid'] = $toBePaid;
			$invoiceData['paidBefore'] = $toBePaid *30/100;
			//echo $invoiceData['paidBefore'];
			$invoiceData['openAmount'] = $toBePaid - ($toBePaid *30/100);
			$invoiceData['stt'] = 0;
			//echo $invoiceData['openAmount'];
			print_r($invoiceData);
			$invoiceDomain = new InvoicesDomain($invoiceData);
			$invoiceID = $invoiceService->createInvoice($context, $result, $invoiceDomain);
			
			foreach ($orderDetailArr as $orderDetail)
			{
				foreach ($_POST as $key => $value)
				{
					if(is_numeric($key) && $key == $orderDetail->getArticle()->getArticleDomain()->getID())
					{
						//$invoiceDetailService->getTheLastInvoiceDetailByOrderIDAndArticleID($context, $result, $orderID, $articleID);
						$shippedQuantity = $shipmentService->getShippedQuantity($context, $result, $_POST['orderID'], $key);
						
						$remainQuantity = $orderDetail->getOrderdetailsDomain()->getQuantity() - ($shippedQuantity + $value);
						
						$invoiceDetailData['invoiceID'] = $invoiceID;
						$invoiceDetailData['articleID'] = $orderDetail->getArticle()->getArticleDomain()->getID();
						$invoiceDetailData['factoryID'] = $_SESSION['user']['ID'];
						$invoiceDetailData['quantity'] = $value;
						$invoiceDetailData['remainQuantity'] = $remainQuantity;
						$invoiceDetailData['priceFact'] = $orderDetail->getOrderdetailsDomain()->getPriceFact();
						$invoiceDetailData['amountFact'] = $value * $orderDetail->getOrderdetailsDomain()->getPriceFact();
						$invoiceDetailData['price'] = $orderDetail->getOrderdetailsDomain()->getPrice();
						$invoiceDetailData['amount'] = $value * $orderDetail->getOrderdetailsDomain()->getPrice();
						$invoiceDetailData['cbm'] = $orderDetail->getOrderdetailsDomain()->getCbm();
						$invoiceDetailDomain = new InvoicedetailsDomain($invoiceDetailData);
						echo "<pre>";
						print_r($invoiceDetailDomain);
						$invoiceDetailService = new InvoiceDetailService();
						$invoiceDetailService->createInvoiceDetail($context, $result, $invoiceDetailDomain);
						
					}
				}
				
			}
			
			$invoice = $invoiceService->getInvoiceByInvoiceID($context, $result, $invoiceID);
			$paymentService->createPaymentByInvoice($context, $result, $invoice);
			$file = $reportService->generateInvoicePDFFile($context, $result, $invoice);
			$fileName = $invoice->getInvoicesDomain()->getInvoiceNumber().'.pdf';
			$invoiceID = $invoice->getInvoicesDomain()->getInvoiceID();
			$toEmail = $glb['contactEmail'];
			$fromEmail = $invoice->getFactory()->getFactoryDomain()->getEmail();
			$emailService->sendEmailNewInvoiceFromFactory($context, $result, $fromEmail, $toEmail, $invoiceID, $fileName, $file);
			header("Location:index.php?func=pi&opt=listPIFactory");
		}
		else
		header("Location:index.php?func=dash");
		break;
		
	case "confirmCheckedInvoice":
		if($permit == true)
		{
			$invoiceService = new InvoiceService();
			$orderService = new OrdersService();
			$invoiceDetailService = new InvoiceDetailService();
			echo "updating...";
			print_r($_POST);
			echo $_POST['orderID'];
			$orderDomain = $orderService->getOrderDomainByOrderID($context, $result, $_POST['orderID']);
			$customerID = $orderDomain->getConsignee();
			foreach ($_POST as $key => $invoiceID)
			{
				if($key != 'orderID' && $key != 'btn_submit')
				{
					echo $invoiceID;
					$invoiceService->updateStatusByInvoiceID($context, $result, $invoiceID, 1);
					$invoice = $invoiceService->getInvoiceByInvoiceID($context, $result, $invoiceID);
					$invoiceNumber = $invoiceService->getMaxInvoiceNumber($context, $result);
					if($invoiceNumber >= $num['invoiceNumber'])
					{
						$invoiceNumber = $invoiceNumber + 1;
					}
					else 
					{
						$invoiceNumber = $num['invoiceNumber'];
					}
					$invoiceDomain = $invoice->getInvoicesDomain();
					$invoiceDomain->setCustomerID($customerID);
					$invoiceDomain->setInvoiceNumber($invoiceNumber);
					//$invoiceIDNew = $invoiceService->createInvoice($context, $result, $invoiceDomain);
					$invoiceDetailArr = $invoice->getInvoiceDetailArr();
					$totalAmount = 0;
					$comm = $invoice->getInvoicesDomain()->getCommission();
					$vat = $invoice->getInvoicesDomain()->getVAT();
					foreach ($invoiceDetailArr as $invoiceDetail)
					{
						$totalAmount = $totalAmount + $invoiceDetail->getInvoicedetailsDomain()->getAmount();
					}
					$totalAfterComm = $totalAmount + ($totalAmount * $comm/100);
					$toBePaid = $totalAfterComm + ($totalAfterComm * $vat/100);
					//echo $toBePaid;
					$invoiceDomain->setTotalAmount($totalAmount);
					$invoiceDomain->setToBePaid($toBePaid);
					$paidBefore = $toBePaid *30/100;
					$invoiceDomain->setPaidBefore($paidBefore);
					$openAmount = $toBePaid - ($toBePaid *30/100);
					$invoiceDomain->setOpenAmount($openAmount);
					//$invoiceData['toBePaid'] = $toBePaid;
					//$invoiceData['paidBefore'] = $toBePaid *30/100;
					//echo $invoiceData['paidBefore'];
					//$invoiceData['openAmount'] = $toBePaid - ($toBePaid *30/100);
					$invoiceIDNew = $invoiceService->createInvoice($context, $result, $invoiceDomain);
					foreach ($invoiceDetailArr as $invoiceDetail)
					{
						$invoiceDetailDomain = $invoiceDetail->getInvoicedetailsDomain();
						$invoiceDetailDomain->setInvoiceID($invoiceIDNew);
						$invoiceDetailService->createInvoiceDetail($context, $result, $invoiceDetailDomain);
					}
					$invoiceNew = $invoiceService->getInvoiceByInvoiceID($context, $result, $invoiceIDNew);
					$file = $reportService->generateInvoicePDFFile($context, $result, $invoiceNew);
					$fileName = $invoiceNew->getInvoicesDomain()->getInvoiceNumber().'.pdf';
					$fromEmail = $glb['contactEmail'];
					$toEmail = $invoiceNew->getCustomer()->getCustomerDomain()->getEmail();
					$emailService->sendEmailNewInvoiceToCustomer($context, $result, $fromEmail, $toEmail, $invoiceIDNew, $fileName, $file);
				}
				
			}
			
			header("Location:index.php?func=invoice&opt=viewInvoice&id=".$_POST['orderID']);
		}
		else
		header("Location:index.php?func=dash");
		break;
			
	default:
		echo "khong co tinh nang nay";
		break;
}
?>